<template>
  <div>
    <!-- <h1>{{ message }}</h1> -->
    <el-drawer size="50%" :visible="drawer" :direction="direction" @close="closeFn">
      <div class="content">
        <div class="title">
          {{ title }}
        </div>
        <div class="one">
          <div class="tit">
            <span style="
                width: 5px;
                background-color: #0a92ec;
                height: 15px;
                display: inline-block;
                margin-right: 5px;
              "></span>昨日<span class="btn" @click="toDetail('1days')">进入详情</span>
          </div>
          <div class="echarts1" id="pieEcahrt"></div>
        </div>
        <div class="two">
          <div class="tit">
            <span style="
                width: 5px;
                background-color: #0a92ec;
                height: 15px;
                display: inline-block;
                margin-right: 5px;
              "></span>近7日<span class="btn" @click="toDetail('7days')">进入详情</span>
            <span style="white-space: pre;">{{ title1 }}</span>
          </div>
          <div class="echarts1" id="zhexian1"></div>
        </div>
        <div class="three">
          <div class="tit">
            <span style="
                width: 5px;
                background-color: #0a92ec;
                height: 15px;
                display: inline-block;
                margin-right: 5px;
              "></span>近一个月<span class="btn" @click="toDetail('30days')">进入详情</span>
            <span style="white-space: pre;">{{ title2 }}</span>
          </div>
          <div class="echarts1" id="zhexian2"></div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { reqStoreById } from "@/api/finance";
import * as echarts from "echarts/core";
import { DecimalUtils } from "@/utils/math";
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
} from "echarts/components";
import { PieChart, BarChart, LineChart } from "echarts/charts";
import { LabelLayout, UniversalTransition } from "echarts/features";
import { LegendComponent } from 'echarts/components';
import { CanvasRenderer } from "echarts/renderers";
import { parseTime4 } from "@/utils"

echarts.use([
  GridComponent,
  BarChart,
  LineChart,
  UniversalTransition,
  TitleComponent,
  TooltipComponent,
  PieChart,
  CanvasRenderer,
  LabelLayout,
  LegendComponent
]);
export default {
  name: "Drawer",
  props: {
    drawer: {
      default: false,
      type: Boolean,
    },
  },
  data() {
    return {
      direction: "rtl",
      title: '',
      title1: '', // 7日的标题
      title2: '', // 30日的标题
      name: '', // 门店名称
      yearsToday: [],
      sevenArr: [],
      thirtyArr: [],
      storeId: "",
    };
  },
  methods: {
    async showDetails(id, name) {
      let res = await reqStoreById({ storeId: id });
      this.storeId = id;
      if (res.code === 200) {
        this.initPie(res.data.yesterdayMap);
        this.initSecond(res.data.pastMonthMap);
        this.initSecond2(res.data.pastSevenMap);
        this.name = name;
      } else {
        // this.$message.error(res.message)
      }
    },
    closeFn() {
      this.$emit("update:drawer", false);
    },
    initPie(option) {
      let tlt = 0;
      let profit = 0;
      // 创建一个当前时间的 Date 对象
      let yearsToday = Date.now();
      yearsToday -= 86400000;

      // 拼接成 "YYYY-mm-dd" 的格式
      const formattedDate = parseTime4(yearsToday);
      this.yearsToday = [formattedDate, formattedDate];


      this.$nextTick(() => {
        this.title = `门店名称:${this.name}                                              订单金额：${tlt}                         供应链分润金额：${profit}`;
      })
      if (JSON.stringify(option) !== "{}") {
        tlt = option.order[`${Object.keys(option.order)[0]}`];
        profit = option.profit[`${Object.keys(option.profit)[0]}`];
      }
      option = {
        tooltip: {
          trigger: "item",
        },
        color: ["#2471FE", "#f79d36"],
        // A code block
        title: {
          show: true,
          text: "订单金额\n\n" + tlt + "元", //要显示的文本
          left: "center",
          top: "center",
          textStyle: {
            color: "rgb(76, 75, 73)",
            fontSize: "14",
          },
        },
        legend: {
          orient: 'vertical',
          left: 'right'
        },
        series: [
          {
            // name: "门店营业额",
            type: "pie",
            radius: ["50%", "70%"],
            avoidLabelOverlap: false,
            labelLine: {
              length2: 17,
              length: 22,
            },
            label: {
              formatter: "{c}元",
            },
            data: [
              { value: profit, name: "供应链分润金额" },
              { value: DecimalUtils.subtract(tlt, profit), name: "门店分润金额" },
            ],
          },
        ],
      };
      var chartDom = document.getElementById("pieEcahrt");
      var myChart = echarts.init(chartDom);
      option && myChart.setOption(option);
    },
    // 30日表
    initSecond(option) {
      let dataArr = this.getPrevious7Days(30);
      // 订单总额
      let valueArr = [];
      // 分润金额
      let valueArr1 = [];
      if (JSON.stringify(option) !== "{}") {
        let order = option.order;
        let profit = option.profit;
        for (let i = 0; i < dataArr.length; i++) {
          if (!order[dataArr[i]]) {
            valueArr.push(0);
            valueArr1.push(0);
          } else {
            valueArr.push(order[dataArr[i]]);
            valueArr1.push(profit[dataArr[i]]);
          }
        }
      } else {
        valueArr = [];
        valueArr1 = [];
      }
      let orderMax = Math.max(...valueArr);
      console.log(valueArr, "订单金额");
      console.log(valueArr1, "分润金额");
      let orderAll = 0;
      let profitAll = 0;
      for (let i = 0; i < valueArr.length; i++) {
        orderAll = DecimalUtils.add(orderAll, valueArr[i]);
        profitAll = DecimalUtils.add(profitAll, valueArr1[i]);
      }
      this.title2 = `                                        订单金额：${orderAll}                         供应链分润金额：${profitAll}`;
      option = {
        grid: {
          top: "18%",
          left: "10%",
          right: "10%",
          bottom: "12%",
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#999",
            },
          },
        },
        xAxis: [
          {
            type: "category",
            data: dataArr,
            axisPointer: {
              type: "shadow",
            },
          },
        ],
        yAxis: [
          {
            alignTicks: true,
            type: "value",
            name: "分润金额",
            // interval: 4000,
            max: this.getMaxNumber(orderMax),
            axisLabel: {
              formatter: "{value}元",
            },
          },
          {
            type: "value",
            name: "订单总额",
            // interval: 4000,
            // alignTicks:true,
            max: this.getMaxNumber(orderMax),
            axisLabel: {
              formatter: "{value} 元",
            },
          },
        ],
        series: [
          {
            name: "分润金额",
            type: "bar",
            tooltip: {
              valueFormatter: function (value) {
                return value + "元";
              },
            },
            data: valueArr1,
          },
          {
            name: "订单总额",
            type: "line",
            symbolSize: 8,
            symbol: "circle",
            smooth: true,
            yAxisIndex: 1,
            tooltip: {
              valueFormatter: function (value) {
                return value + "元";
              },
            },
            data: valueArr,
          },
        ],
      };
      var chartDom1 = document.getElementById("zhexian2");
      var myChart1 = echarts.init(chartDom1);
      option && myChart1.setOption(option);
    },
    // 七日表
    initSecond2(option) {
      let dataArr = this.getPrevious7Days(7);
      // 订单总额
      let valueArr = [];
      // 分润金额
      let valueArr1 = [];
      if (JSON.stringify(option) !== "{}") {
        let order = option.order;
        let profit = option.profit;
        for (let i = 0; i < dataArr.length; i++) {
          if (!order[dataArr[i]]) {
            valueArr.push(0);
            valueArr1.push(0);
          } else {
            valueArr.push(order[dataArr[i]]);
            valueArr1.push(profit[dataArr[i]]);
          }
        }
      } else {
        valueArr = [0, 0, 0, 0, 0, 0, 0];
        valueArr1 = [0, 0, 0, 0, 0, 0, 0];
      }
      let orderMax = Math.max(...valueArr);
      console.log(valueArr, "订单金额");
      console.log(valueArr1, "分润金额");
      let orderAll = 0;
      let profitAll = 0;
      for (let i = 0; i < valueArr.length; i++) {
        orderAll = DecimalUtils.add(orderAll, valueArr[i]);
        profitAll = DecimalUtils.add(profitAll, valueArr1[i]);
      }
      this.title1 = `                                              订单金额：${orderAll}                         供应链分润金额：${profitAll}`;
      option = {
        grid: {
          top: "19%",
          left: "10%",
          right: "10%",
          bottom: "15%",
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#999",
            },
          },
        },
        xAxis: [
          {
            type: "category",
            data: dataArr,
            axisPointer: {
              type: "shadow",
            },
          },
        ],
        yAxis: [
          {
            alignTicks: true,
            type: "value",
            name: "分润金额",
            // interval: 4000,
            max: this.getMaxNumber(orderMax),
            min: 0,
            axisLabel: {
              formatter: "{value}元",
            },
          },
          {
            type: "value",
            name: "订单总额",
            // interval: 4000,
            // alignTicks:true,
            max: this.getMaxNumber(orderMax),
            min: 0,
            axisLabel: {
              formatter: "{value} 元",
            },
          },
        ],
        series: [
          {
            name: "分润金额",
            type: "bar",
            tooltip: {
              valueFormatter: function (value) {
                return value + "元";
              },
            },
            data: valueArr1,
          },
          {
            name: "订单总额",
            type: "line",
            symbolSize: 8,
            symbol: "circle",
            smooth: true,
            yAxisIndex: 1,
            tooltip: {
              valueFormatter: function (value) {
                return value + "元";
              },
            },
            data: valueArr,
          },
        ],
      };
      var chartDom1 = document.getElementById("zhexian1");
      var myChart1 = echarts.init(chartDom1);
      option && myChart1.setOption(option);
    },
    toDetail(str) {
      if (str === "1days") {
        this.$router.push({
          path: "independentAccount",
          query: {
            id: this.storeId,
            startTime: this.yearsToday[0],
            endTime: this.yearsToday[1],
          },
        });
      } else if (str === "7days") {
        this.$router.push({
          path: "independentAccount",
          query: {
            id: this.storeId,
            startTime: this.sevenArr[0],
            endTime: this.sevenArr[1],
          },
        });
      } else if (str === "30days") {
        this.$router.push({
          path: "independentAccount",
          query: {
            id: this.storeId,
            startTime: this.thirtyArr[0],
            endTime: this.thirtyArr[1],
          },
        });
      }
    },
    getPrevious7Days(day) {
      let dates = [];
      let currentDate = new Date();

      for (let i = 1; i <= day; i++) {
        let date = new Date(currentDate);
        date.setDate(date.getDate() - i);
        let formattedDate = date.toISOString().split('T')[0];
        // formattedDate = formattedDate.split('-').join('/');
        dates.unshift(formattedDate);
      }
      if (day === 7) {
        this.sevenArr = [dates[0], dates[6]]
      } else {
        this.thirtyArr = [dates[0], dates[29]]
      }
      if (dates.length === 30) {
        dates = dates.map(date => date.substring(5))
      }
      return dates;
    },
    getMaxNumber(value) {
      if (value < 0.1) {
        return 0.1;
      } else if (value < 0.4) {
        return 0.4;
      } else if (value < 1) {
        return 1;
      } else if (value < 10) {
        return 10;
      } else if (value < 50) {
        return 50;
      } else if (value < 100) {
        return 100;
      } else if (value < 1000) {
        return Math.ceil(value / 100) * 100;
      } else if (value < 10000) {
        return Math.ceil(value / 1000) * 1000;
      } else if (value < 100000) {
        return Math.ceil(value / 10000) * 10000;
      } else if (value < 1000000) {
        return Math.ceil(value / 1000000) * 1000000;
      } else {
        return value;
      }
    }
  },
};
</script>
<style scoped lang="scss">
.content {
  padding: 0 20px;
  position: relative;

  .title {
    position: absolute;
    top: -55px;
    white-space: pre;
  }

  /* overflow: scroll; */
  .one {
    height: 1.0938rem;
    /* height: 500px; */
    display: flex;
    border-bottom: 2px solid #ccc;
    margin-bottom: 20px;

    /* background-color: #f79d36; */
    .tit {
      width: 40%;
      vertical-align: middle;
    }

    #pieEcahrt {
      width: 60%;
      height: 1.0417rem;
      /* padding-left: 200px; */
    }
  }

  .two {
    height: 1.4583rem;
    /* display: flex; */
    border-bottom: 2px solid #ccc;
    margin-bottom: 20px;

    .tit {
      /* width: 40%; */
      vertical-align: middle;
    }

    #zhexian1 {
      width: 100%;
      height: 1.0938rem;
      /* background-color: #e8e4df; */
    }
  }

  .three {
    height: 1.4583rem;
    border-bottom: 2px solid #ccc;

    .tit {
      /* width: 40%; */
      vertical-align: middle;
    }

    #zhexian2 {
      width: 100%;
      height: 1.1979rem;
      /* background-color: #e8e4df; */
    }
  }

  .btn {
    display: inline-block;
    background-color: #2494e3;
    margin-left: 5px;
    color: aliceblue;
    padding: 8px;
    border-radius: 5px;
    cursor: pointer;
  }
}
</style>
<style>
.el-drawer.rtl {
  overflow: scroll;
}

.el-drawer.rtl #el-drawer__title {
  white-space: pre;
  /* pointer-events: none; */
}

.el-drawer__container ::-webkit-scrollbar {
  display: none;
}
</style>
